package com.zjdiepu.www.proxy.biz.impl.transfer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.diepu.www.client.proxy.partner.request.own.DiepuYwBusinessBuyersRequest;
import com.diepu.www.client.proxy.partner.request.own.DiepuYwBusinessLoanRequest;
import com.diepu.www.client.proxy.partner.request.own.DiepuYwOpenCardHzicbcRequest;
import com.diepu.www.client.proxy.partner.request.own.DiepuYwOpenCardHzicbcSubRequest;
import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.core.BaseService;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.status.OpenCardStatus;
import com.zjdiepu.www.base.enums.type.CreditPeopleType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.common.consts.SystemConsts;
import com.zjdiepu.www.common.util.DateUtil;
import com.zjdiepu.www.config.ScheduleProxyConfig;
import com.zjdiepu.www.diepu.biz.IDiepuProxyService;
import com.zjdiepu.www.proxy.biz.transfer.INewTransaction;
import com.zjdiepu.www.proxy.biz.transfer.ITransferYwOpenCardHzicbcService;
import com.zjdiepu.www.proxy.biz.transfer.ITransferYwOrdernoBankService;
import com.zjdiepu.www.proxy.dao.transfer.TransferYwBusinessBuyerMapper;
import com.zjdiepu.www.proxy.dao.transfer.TransferYwBusinessLoanMapper;
import com.zjdiepu.www.proxy.dao.transfer.TransferYwOpenCardHzicbcMapper;
import com.zjdiepu.www.proxy.dao.transfer.TransferYwOpenCardHzicbcSubMapper;
import com.zjdiepu.www.proxy.dao.transfer.TransferYwOrdernoBankMapper;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferYwBusinessBuyer;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferYwBusinessLoan;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferYwOpenCardHzicbc;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferYwOpenCardHzicbcSub;
import com.zjdiepu.www.proxy.model.dto.transfer.TransferYwOrdernoBank;
import com.zjdiepu.www.proxy.model.ext.transfer.TransferYwOpenCardHzicbcExt;
import com.zjdiepu.www.util.ExceptionHelper;

/**
 * 中转_yw_开卡信息_杭州工行Service层操作实现<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年12月13日 17时50分<br/>
 * @since 1.0<br/>
 */
@Service
public class TransferYwOpenCardHzicbcServiceImpl extends BaseService implements ITransferYwOpenCardHzicbcService {
	public static final Logger logger = LoggerFactory.getLogger(TransferYwOpenCardHzicbcServiceImpl.class);
	@Resource
	protected ScheduleProxyConfig scheduleProxyConfig;
	@Autowired
	private TransferYwOpenCardHzicbcMapper transferYwOpenCardHzicbcMapper;
	@Autowired
	private TransferYwOpenCardHzicbcSubMapper transferYwOpenCardHzicbcSubMapper;
	@Autowired
	private TransferYwBusinessLoanMapper transferYwBusinessLoanMapper;
	@Autowired
	private TransferYwOrdernoBankMapper transferYwOrdernoBankMapper;
	@Resource
	private INewTransaction newTransaction;
	@Autowired
	private TransferYwBusinessBuyerMapper transferYwBusinessBuyerMapper;
	@Resource
	private IDiepuProxyService diepuProxyService;
	@Resource
	private ITransferYwOrdernoBankService transferYwOrdernoBankService;
	
	@Override
	public void saveUpdateAndDelete(TransferYwOpenCardHzicbc transferYwOpenCardHzicbc, OperateType operType) {
		switch (operType) {
		case add:
			transferYwOpenCardHzicbc.initInsertData(transferYwOpenCardHzicbc.getModifier(), transferYwOpenCardHzicbc.getModifierName());
			transferYwOpenCardHzicbcMapper.insert(transferYwOpenCardHzicbc);
			break;
		case edit:
			transferYwOpenCardHzicbc.initUpdateData(transferYwOpenCardHzicbc.getModifier(), transferYwOpenCardHzicbc.getModifierName());
			// 影响的记录数
			int updateCount = transferYwOpenCardHzicbcMapper.updateByPrimaryKeySelective(transferYwOpenCardHzicbc);
			if(updateCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(updateCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		case delete:
			transferYwOpenCardHzicbc.initDeleteData(transferYwOpenCardHzicbc.getModifier(), transferYwOpenCardHzicbc.getModifierName());
			// 影响的记录数
			int deleteCount = transferYwOpenCardHzicbcMapper.updateByPrimaryKeySelective(transferYwOpenCardHzicbc);
			if(deleteCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(deleteCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		default:
			break;
		}
	}
	
	@Override
	public List<TransferYwOpenCardHzicbc> selectByExt(TransferYwOpenCardHzicbcExt transferYwOpenCardHzicbcExt) {
		return transferYwOpenCardHzicbcMapper.selectByExt(transferYwOpenCardHzicbcExt);
	}
	
	@Override
	public int countByExt(TransferYwOpenCardHzicbcExt transferYwOpenCardHzicbcExt){
		return transferYwOpenCardHzicbcMapper.countByExt(transferYwOpenCardHzicbcExt);
	}
	
	@Override
	public TransferYwOpenCardHzicbc selectById(String id) {
		return transferYwOpenCardHzicbcMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public void clearEmpty(Set<String> fieldNames, String id) {
		if(CollectionUtils.isNotEmpty(fieldNames)){
			transferYwOpenCardHzicbcMapper.clearEmpty(fieldNames, id);
		}
	}
	
	@Override
	public int countRefined(TransferYwOpenCardHzicbc transferYwOpenCardHzicbc) {
		return transferYwOpenCardHzicbcMapper.countRefined(transferYwOpenCardHzicbc);
	}

	@Override
	public TransferYwOpenCardHzicbc selectRefined(TransferYwOpenCardHzicbc transferYwOpenCardHzicbc) {
		return transferYwOpenCardHzicbcMapper.selectRefined(transferYwOpenCardHzicbc);
	}
	
	@Override
	public int deletedRefined(TransferYwOpenCardHzicbc transferYwOpenCardHzicbc) {
		return transferYwOpenCardHzicbcMapper.deletedRefined(transferYwOpenCardHzicbc);
	}

	@Override
	public boolean repeat(TransferYwOpenCardHzicbc transferYwOpenCardHzicbc) {
		int count = countRefined(transferYwOpenCardHzicbc);
		if(count > 1) {
			return true;
		}
		if(count == 0) {
			return false;
		}
		
		if(StringUtils.isBlank(transferYwOpenCardHzicbc.getId())) {
			return true;
		}
		TransferYwOpenCardHzicbc dbItem = selectRefined(transferYwOpenCardHzicbc);
		if(null == dbItem) {
			return false;
		}
		return !transferYwOpenCardHzicbc.getId().equals(dbItem.getId());
	}
	
	@Override
	public int updateBatch(String modifier, String modifierName, Integer dpStatus, List<String> ids) {
		Integer current = (int)(System.currentTimeMillis() / 1000);
		return transferYwOpenCardHzicbcMapper.updateBatch(modifier, modifierName, current, dpStatus, ids);
	}
	
	@Override
	public int insertBatch(List<TransferYwOpenCardHzicbc> transferYwOpenCardHzicbcs) {
		return transferYwOpenCardHzicbcMapper.insertBatch(transferYwOpenCardHzicbcs);
	}
	
	@Override
	public void applyIcbcOpenCardInterface(DiepuYwOpenCardHzicbcRequest ywOpenCardHzicbc,
			DiepuYwOpenCardHzicbcSubRequest ywOpenCardHzicbcSub,
			DiepuYwBusinessLoanRequest ywBusinessLoan,DiepuYwBusinessBuyersRequest ywBusinessBuyers) {
		String orderBankId="";
//		TransferYwOrdernoBank transferYwOrdernoBank=new TransferYwOrdernoBank();
//		transferYwOrdernoBank.setBusiId(ywOpenCardHzicbc.getBusiId());
//		transferYwOrdernoBank=transferYwOrdernoBankMapper.selectRefined(transferYwOrdernoBank);
		String busiId = ywOpenCardHzicbc.getBusiId();
		if(StringUtils.isBlank(busiId) ) {
			ExceptionHelper.thow(ResultFlagType.PARAM_EMPTY.getCode().toString(),"申请开卡时，业务ID为空");
		}
		
		List<TransferYwOrdernoBank> transferYwOrdernoBank = transferYwOrdernoBankService.getByBusiId(busiId);
		if(transferYwOrdernoBank == null){
			logger.error("申请开卡时，对应的银行订单号为空，业务ID：{}.",busiId);
			ExceptionHelper.thow(ResultFlagType.PARAM_EMPTY.getCode().toString(),"对应的银行订单号为空");
		}
		//防止同一个订单id对应了多个工行订单号，假如这个验证，pan，4.3
		if(transferYwOrdernoBank.size() > 1){
			logger.error("申请开卡时，对应的银行订单号有多个，业务ID：{}.",busiId);
			ExceptionHelper.thow(ResultFlagType.PARAM_EMPTY.getCode().toString(),"对应的银行订单号有多个");
		}
		orderBankId=transferYwOrdernoBank.get(0).getOrdeRno();
		
		//将yw_开卡信息_杭州工行对象 写入 transfer_yw_open_card_hzicbc
		TransferYwOpenCardHzicbc transferYwOpenCardHzicbc=new TransferYwOpenCardHzicbc();
		transferYwOpenCardHzicbc.setBusiId(ywOpenCardHzicbc.getBusiId());
		transferYwOpenCardHzicbc.setDpStatus(1);
		transferYwOpenCardHzicbc = transferYwOpenCardHzicbcMapper.selectRefined(transferYwOpenCardHzicbc);
		if(transferYwOpenCardHzicbc!=null){
			transferYwOpenCardHzicbc.setDpStatus(3);
			transferYwOpenCardHzicbcMapper.updateByPrimaryKeySelective(transferYwOpenCardHzicbc);
			
			TransferYwOpenCardHzicbc transferYwOpenCardHzicbc0=new TransferYwOpenCardHzicbc();
			BeanUtils.copyProperties(ywOpenCardHzicbc, transferYwOpenCardHzicbc0);
			transferYwOpenCardHzicbc0.initInsertData(SystemConsts.DEFAULT_ID, "无");
			transferYwOpenCardHzicbc0.setInformStatus("0");
			transferYwOpenCardHzicbc0.setTryCount(0);
			transferYwOpenCardHzicbc0.setBankOrderNo(orderBankId);
			transferYwOpenCardHzicbcMapper.insert(transferYwOpenCardHzicbc0);
		}else{
			TransferYwOpenCardHzicbc transferYwOpenCardHzicbc1=new TransferYwOpenCardHzicbc();
			BeanUtils.copyProperties(ywOpenCardHzicbc, transferYwOpenCardHzicbc1);
			transferYwOpenCardHzicbc1.initInsertData(SystemConsts.DEFAULT_ID, "无");
			transferYwOpenCardHzicbc1.setInformStatus("0");
			transferYwOpenCardHzicbc1.setTryCount(0);
			transferYwOpenCardHzicbc1.setBankOrderNo(orderBankId);
			transferYwOpenCardHzicbcMapper.insert(transferYwOpenCardHzicbc1);
		}
		
		//将yw_开卡信息_杭州工行_子表对象 写入 中转_yw_开卡信息_杭州工行_子表
		TransferYwOpenCardHzicbcSub transferYwOpenCardHzicbcSub=new TransferYwOpenCardHzicbcSub();
		transferYwOpenCardHzicbcSub.setBusiId(ywOpenCardHzicbcSub.getBusiId());
		transferYwOpenCardHzicbcSub.setDpStatus(1);
		transferYwOpenCardHzicbcSub = transferYwOpenCardHzicbcSubMapper.selectRefined(transferYwOpenCardHzicbcSub);
		if(transferYwOpenCardHzicbcSub!=null){
			transferYwOpenCardHzicbcSub.setDpStatus(3);
			transferYwOpenCardHzicbcSubMapper.updateByPrimaryKeySelective(transferYwOpenCardHzicbcSub);
			
			TransferYwOpenCardHzicbcSub transferYwOpenCardHzicbc0=new TransferYwOpenCardHzicbcSub();
			BeanUtils.copyProperties(ywOpenCardHzicbcSub, transferYwOpenCardHzicbc0);
			transferYwOpenCardHzicbc0.initInsertData(SystemConsts.DEFAULT_ID, "开卡");
			transferYwOpenCardHzicbcSubMapper.insert(transferYwOpenCardHzicbc0);
		}else{
			TransferYwOpenCardHzicbcSub transferYwOpenCardHzicbcSub1=new TransferYwOpenCardHzicbcSub();
			BeanUtils.copyProperties(ywOpenCardHzicbcSub, transferYwOpenCardHzicbcSub1);
			transferYwOpenCardHzicbcSub1.initInsertData(SystemConsts.DEFAULT_ID, "开卡");
			transferYwOpenCardHzicbcSubMapper.insert(transferYwOpenCardHzicbcSub1);
		}
		
		//将yw_贷款信息对象 写入（或者更新） transfer_yw_business_loan 
		TransferYwBusinessLoan transferYwBusinessLoan= new TransferYwBusinessLoan();
		transferYwBusinessLoan.setBusiId(ywBusinessLoan.getBusiId());
		transferYwBusinessLoan=transferYwBusinessLoanMapper.selectRefined(transferYwBusinessLoan);
		if(transferYwBusinessLoan!=null){
			BeanUtils.copyProperties(ywBusinessLoan, transferYwBusinessLoan);
			transferYwBusinessLoan.initUpdateData(SystemConsts.DEFAULT_ID, "开卡");
			transferYwBusinessLoanMapper.updateByPrimaryKeySelective(transferYwBusinessLoan);
		}else{
			TransferYwBusinessLoan transferYwBusinessLoan1= new TransferYwBusinessLoan();
			BeanUtils.copyProperties(ywBusinessLoan, transferYwBusinessLoan1);
			transferYwBusinessLoan1.initInsertData(SystemConsts.DEFAULT_ID, "开卡");
			transferYwBusinessLoan1.setId(ywBusinessLoan.getId());
			transferYwBusinessLoanMapper.insert(transferYwBusinessLoan1);
		}
		//将yw_购车人对象 写入（或者更新）
		TransferYwBusinessBuyer transferYwBusinessBuyer=new TransferYwBusinessBuyer();
		transferYwBusinessBuyer.setBusiId(ywOpenCardHzicbc.getBusiId());
		transferYwBusinessBuyer.setCarManType(CreditPeopleType.ZHU_JIE_REN.getCode());
		transferYwBusinessBuyer=transferYwBusinessBuyerMapper.selectRefined(transferYwBusinessBuyer);
		if(transferYwBusinessBuyer!=null){
			BeanUtils.copyProperties(ywBusinessBuyers, transferYwBusinessBuyer);
			transferYwBusinessBuyerMapper.updateByPrimaryKeySelective(transferYwBusinessBuyer);
		}else{
			TransferYwBusinessBuyer transferYwBusinessBuyer1=new TransferYwBusinessBuyer();
			BeanUtils.copyProperties(ywBusinessBuyers, transferYwBusinessBuyer1);
			transferYwBusinessBuyer1.initInsertData(SystemConsts.DEFAULT_ID, "无");
			transferYwBusinessBuyerMapper.insert(transferYwBusinessBuyer1);
		}
		
		//写一个时间为2分钟（可配）只有的 从主程序获取附件列表 的定时任务；ScheduleProxyConfig
		newTransaction.getAttachments(orderBankId, ywOpenCardHzicbc.getBusiId(),DateUtil.increaseMinute(new Date(), scheduleProxyConfig.getSynAttachementsDiepu() / 1000 / 60));
		
		//写一个时间为5分钟（可配）之后的下载附件定时任务；
		newTransaction.downLoadAttachments(orderBankId, ywOpenCardHzicbc.getBusiId(),DateUtil.increaseMinute(new Date(), scheduleProxyConfig.getFileDownloadQiniu() / 1000 / 60));
		
		//写一个时间为10分钟（可配）之后的向工行申请开卡的定时任务；
		newTransaction.saveToHzicbc(orderBankId, ywOpenCardHzicbc.getBusiId(),DateUtil.increaseMinute(new Date(), scheduleProxyConfig.getOpenCardSussess() / 1000 / 60));
	}
	
	public void updateYwOpenCardicbc(String realPath){
		File file=new File(realPath);
		try(BufferedReader br =new BufferedReader( new InputStreamReader(new FileInputStream(file), "GBK"));){
            String s = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
            	if(s.contains("|")){
            		String[] txts=s.split("\\|");
        			TransferYwOrdernoBank transferYwOrdernoBank2 = transferYwOrdernoBankService.getByOrderNo(txts[3].trim());
        			if(transferYwOrdernoBank2!=null){
        				Integer opcardStatus=0;
        				TransferYwOpenCardHzicbc transferYwOpenCardHzicbc=new TransferYwOpenCardHzicbc();
        				transferYwOpenCardHzicbc.setBusiId(transferYwOrdernoBank2.getBusiId());
        				transferYwOpenCardHzicbc.setDpStatus(DpStatus.NORMAL.getCode());
        				transferYwOpenCardHzicbc=transferYwOpenCardHzicbcMapper.selectRefined(transferYwOpenCardHzicbc);
        				if(transferYwOpenCardHzicbc!=null){
        					try {
        						transferYwOpenCardHzicbc.setOpenDate(sf.parse(txts[4].trim()));
        					} catch (ParseException e) {
        						e.printStackTrace();
        					}
        					transferYwOpenCardHzicbc.setCardno(txts[5].trim());
        					transferYwOpenCardHzicbc.setBankStatementDate(Integer.parseInt(txts[10].trim()));
        					transferYwOpenCardHzicbc.setRepaymentDate(Integer.parseInt(txts[11].trim()));
        					if(StringUtils.isNotBlank(txts[9])&&txts[9].equals("0")){
        						opcardStatus=OpenCardStatus.KAI_KA_SHI_BAI.getCode();
        						transferYwOpenCardHzicbc.setReasonBack("卡部退回"); // 增加备注,pan
        					}else{
        						opcardStatus=OpenCardStatus.KAI_KA_CHENG_GONG.getCode();
        					}
        					transferYwOpenCardHzicbc.setOpenCardStatus(opcardStatus);
        					transferYwOpenCardHzicbc.setBankOrderNo(txts[3].trim());
        					transferYwOpenCardHzicbc.setInformStatus("0");
        					transferYwOpenCardHzicbcMapper.updateByPrimaryKeySelective(transferYwOpenCardHzicbc);
        				}
            		}
            	}
            }
        } catch(Exception e){
            e.printStackTrace();
        }
		diepuProxyService.saveOpenCardSuccess();
		diepuProxyService.saveOpenCardFail();
	}
}
